package com.example.waterrecordopengl;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
import android.widget.Toast;
import androidx.core.app.ActivityCompat;

import java.io.IOException;
import java.util.UUID;


public class BluetoothConnector {
    private static final UUID MY_UUID = UUID.randomUUID(); // SPP UUID
    private BluetoothDevice device;
    private BluetoothSocket socket;

    public BluetoothConnector(BluetoothDevice device) {
        this.device = device;
    }

    public void connect(Context context) {
        try {
            if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            Log.i("链接uuid",MY_UUID+"");
            socket = device.createRfcommSocketToServiceRecord(MY_UUID);
            socket.connect();
            // 连接成功
            Toast.makeText(context, "连接成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            // 连接失败处理
            e.printStackTrace();
            Toast.makeText(context, "连接失败"+e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
        }
    }



    public void setData(String msg){
        if (socket != null) {
            try {
                socket.getOutputStream().write(msg.getBytes());
            } catch (IOException e) {
                // 写入数据时出错
            }
        }
    }

    public void disconnect() {
        try {
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            // 关闭连接时出错
        }
    }
}
